#include <unordered_map>
#include <string>
#include <unistd.h>
#include <iostream>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"

static void Usage(const std::string proc)
{
    std::cout << "Usage:\n\t" << proc << " port [ip]" << std::endl;
}
// INADDR_ANY
class UdpServer
{
public:
    UdpServer(int port, std::string ip = "") : port_((uint16_t)port), ip_(ip)
    {
    }
    ~UdpServer()
    {
    }
    void init()
    {
        // 1.创建套接字
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd_ < 0)
        {
            logmessage(FATAL, "socket:%s:%d", strerror(errno), sockfd_);
            exit(1);
        }
        logmessage(DEBUG, "socket create success:%d", sockfd_);
        // 2.填充sockaddr
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        local.sin_addr.s_addr = ip_.empty() ? htonl(INADDR_ANY) : inet_addr(ip_.c_str());
        // 3.bind连接
        if (bind(sockfd_, (const struct sockaddr *)&local, sizeof(local)) == -1)
        {
            logmessage(FATAL, "bind:%s:%d", strerror(errno), sockfd_);
            exit(2);
        }
        logmessage(DEBUG, "socket bind success:%d", sockfd_);
    }
    void start()
    {
        char inbuffer[1024];
        char outbuffer[1024];
        while (true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            //std::cout<<"开始等待——————————————————"<<std::endl;
            ssize_t s=recvfrom(sockfd_, inbuffer, sizeof(inbuffer) - 1, 0,
                     (struct sockaddr *)&peer, &len);

            if (s > 0)
            {
                //'\0'的值就是0，'0'的值是48，这里是存ASCII为0的'\0'
                inbuffer[s] = 0; //当做字符串
            }
            else if (s == -1)
            {
                logmessage(WARNNING, "recvfrom: %s:%d", strerror(errno), sockfd_);
                continue;
            }

            //std::cout<<"666666——————————————————"<<std::endl;
            std::string peerIp= inet_ntoa(peer.sin_addr);
            uint16_t peerPort= ntohs(peer.sin_port);
            checkOnlineUser(peerIp,peerPort,peer);
            logmessage(NOTICE,"[%s:%d]#%s",peerIp.c_str(),peerPort,inbuffer);
            messageRoute(peerIp,peerPort,inbuffer);
        }
    }
    void checkOnlineUser(std::string peerIp,uint16_t peerPort,struct sockaddr_in peer)
    {
        std::string key=peerIp;
        key+=":";
        key+=std::to_string(peerPort);
        auto iter=users.find(key);
        if(iter==users.end())
        {
            //users.insert(make_pair(key,peer));
            users.insert({key,peer});
        }
        else
        {}
 
    }
    void messageRoute(std::string peerIp,uint16_t peerPort,std::string inbuffer)
    {
        std::string message="[";
        message+=peerIp;
        message+=":";
        message+=peerPort;
        message+="]# ";
        message+=inbuffer;
        for(auto user:users)
        {
            sendto(sockfd_,message.c_str(),message.size(),0,
            (struct sockaddr*)&user.second,sizeof(user.second));
        }
    }
private:
    uint16_t port_; // 端口号
    std::string ip_;
    int sockfd_; // 服务器的socket fd信息
    std::unordered_map<std::string,struct sockaddr_in> users;
};
//./udpServer port [ip]
int main(int argc, char *argv[])
{
    // logmessage(NOTICE,"111111111111\n");
    if (argc != 2 && argc != 3)
    {
        Usage(argv[0]);
        exit(3);
    }
    uint16_t port = atoi(argv[1]);
    std::string ip;
    if (argc == 3)
    {
        ip = argv[2];
    }
    UdpServer svr(port, ip);
    svr.init();
    svr.start();
    return 0;
}